<template>
	<view class="uni-column">
		<view class="content" id="content" :style="{height:style.contentViewHeight+'px'}">
			<scroll-view id="scrollview" scroll-y="true" :style="{height:style.contentViewHeight+'px'}" :scroll-with-animation="true"
			 :scroll-top="scrollTop">
				<message-show v-for="(message,index) in messages" :key="index" v-bind:message="message" :id="id" :headImg='headImg' :userimg="userimg"></message-show>
				<view id="bottom"></view>
			</scroll-view>
		</view>
		<view class="foot">

			<chat-input @send-message="getInputMessage"></chat-input>
		</view>
	</view>
</template>

<script>
	import chatInput from '../../components/chatinput.vue';
	import messageShow from '../../components/messageshow.vue';
	import RongIMLib from '../../common/RongIMLib-3.0.6.2-dev.js'
	import Sha1 from '../../common/sha1.min.js'
	var _self;
	var navi = null
	var RongIMClient = RongIMLib

	//认证企业key

	const appkey = '25wehl3u20ntw'
	const appSecret = '0n9qu4SBmbQj'
let im = RongIMClient.init({
					appkey
				})

	var config = {}
	if (navi) {
		config.navi = navi
	}
	export default {
		components: {
			chatInput,
			messageShow
		},
		data() {
			return {
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0,
				},
				scrollTop: 0,
				messages: [],
				title: 'rongyun demo',
				token: '',
				name: '',
				detail:'',
				id:'',
				headImg:"",
				userimg:''
			}
		},

		onLoad(option) {

			_self = this
			this.getOther(option.id)
			this.getToken()
			this.id = option.id
			this.getInfo()
			// this.setwatch()
		},
		created: function() {
			const res = uni.getSystemInfoSync();
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (100); //像素
		},
		methods: {
			//获取个人信息
			getInfo(){
				let id = uni.getStorageSync('userId')
				this.$http.get('/userCenter/getUserInfoById', {id:id}).then(res => {
					if (res.code == '0') {
						this.userimg = res.data.headImg
					
					}
				})
			},
			//获取对方信息
			getOther(id){
				this.$http.get('/patent/getPatentById', {patentId:id}).then(res => {
					if (res.code == 0) {
						
						this.headImg = res.data.userHead
						this.name = res.data.name
						uni.setNavigationBarTitle({ title:res.data.userName })
						
					}
				})
			},
            setwatch(){
				var im = RongIMLib.init({
				  appkey: ' appkey'
				});
				var conversationList = []; // 当前已存在的会话列表
				im.watch({
				  conversation: function(event){
					  console.log(event)
					var updatedConversationList = event.updatedConversationList; // 更新的会话列表
					console.log('更新会话汇总:', updatedConversationList);
					console.log('最新会话列表:', im.Conversation.merge({
						conversationList,
						updatedConversationList
					  }));
				  },
				  message: function(event){
					var message = event.message;
					console.log('收到新消息:', message);
				  },
				  status: function(event){
					var status = event.status;
					console.log('连接状态码:', status);
				  }
				});	
			},
			//模拟服务器端获取token
			getToken() {
				let Nonce = parseInt(Math.random() * 10000000000)
				let Timestamp = parseInt(new Date().getTime() / 1000)

				//生成签名
				let Signature = Sha1(appSecret + Nonce + Timestamp)
				_self.token = uni.getStorageSync("rongToken")
				// _self.token = "U+MwB48mKR5uhG/V69Y5NrwJZFqjEl/O@ap60.cn.rongnav.com;ap60.cn.rongcfg.com"
				setTimeout(() => {
					console.log('客户端初始化并连接融云服务器')
					_self.connectRongIM()
				}, 2000)

			},
			// 连接融云
			
			//客户端连接服务器
			connectRongIM() {
				let that = this
				var user = {
					token: uni.getStorageSync("rongToken")
				};
							
				var conversationList = []; // 当前已存在的会话列表
				im.watch({
					conversation: function(event) {
						console.log(event)
						var updatedConversationList = event.updatedConversationList; // 更新的会话列表
						console.log('更新会话汇总:', updatedConversationList);
						
						console.log('最新会话列表:', im.Conversation.merge({
							conversationList,
							updatedConversationList
						}));
					},
					message: function(event) {
						console.log(event)
						var message = event.message;
						console.log('收到新消息:', message);
						// that.addMessage('home', message.content, false, message.type);
						
					},
					status: function(event) {
						var status = event.status;
						console.log('连接状态码:', status);
					}
				});
				im.connect(user).then(function(user) {
					this.userId = user.id
					console.log('链接成功, 链接用户 id 为: ', user.id);
					
				}).catch(function(error) {
					console.log('链接失败: ', error.code, error.msg);
				});


			},
			//模拟服务器端向单个客户端发送消息
			serverSendMessage(user, content, hasSub, type) {
				let that = this
				var conversation = im.Conversation.get({
					targetId: that.userId,
					type: RongIMLib.CONVERSATION_TYPE.PRIVATE
				});
				conversation.send({
					messageType: RongIMLib.MESSAGE_TYPE.TEXT, // 'RC:TxtMsg'
					content: {
						 content: content // 文本内容
					}
				}).then(function(message) {
					console.log('发送文字消息成功', message);
					that.addMessage('customer', message.content, false, message.type);
				});
				let Nonce = parseInt(Math.random() * 10000000000)
				let Timestamp = parseInt(new Date().getTime() / 1000)
				let Signature = Sha1(appSecret + Nonce + Timestamp)
				
				
			},




			getInputMessage: function(message) { //获取子组件的输入数据
				console.log(message);
				this.serverSendMessage('customer', message.content, false, message.type)
			
				// this.toRobot(message);
			},
			addMessage: function(user, content, hasSub, type) {
				console.log(user)
				console.log(content)
				console.log(hasSub)
				console.log(type)
				var that = this;
				that.messages.push({
					user: user,
					content: content,
					hasSub: hasSub,
					type: type
				});
			},
			scrollToBottom: function() {
				var that = this;
				var query = uni.createSelectorQuery();
				query.selectAll('.m-item').boundingClientRect();
				query.select('#scrollview').boundingClientRect();
				query.exec(function(res) {
					that.style.mitemHeight = 0;
					res[0].forEach(function(rect) {
						// console.info(rect.height);
						that.style.mitemHeight = that.style.mitemHeight + rect.height + 20;
					});
					if (that.style.mitemHeight > that.style.contentViewHeight) {
						that.scrollTop = that.style.mitemHeight - that.style.contentViewHeight;
					}
				});
			},
			// 接收消息
			toRobot: function(message) {
				// console.log(message)
				this.addMessage('home', message.content, false, message.type);
				// this.addMessage('home', res.data.text, false,);
				this.scrollToBottom();
				var apiUrl = 'http://192.168.0.101:80/api';
				uni.request({
					url: apiUrl,
					data: {
						"key": 'acfbca724ea1b5db96d2eef88ce677dc',
						"info": info,
						"userid": 'uni-test'
					},
					success: (res) => {

						console.log('request success:' + res.data.text);
					},
					fail: (err) => {
						console.log('request fail', err);
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						})
					}
				});
			}
		}
	}
</script>

<style scoped>
	.uni-column {
		display: flex;
		flex-direction: column;
	}

	.content {
		display: flex;
		flex: 1;
		margin-bottom: 100rpx;

	}

	.foot {
		position: fixed;
		width: 100%;
		height: 90rpx;
		min-height: 90rpx;
		left: 0px;
		bottom: 0px;
		overflow: hidden;
	}

	.simal {
		width: 20upx;
		height: 20upx;
	}
</style>
